package com.lagou.encoder;

import com.alibaba.fastjson.JSON;
import com.lagou.proto.RpcRequest;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;

import java.nio.ByteBuffer;


public class NettyClientDecoder extends LengthFieldBasedFrameDecoder {


    public NettyClientDecoder() {
        super(Integer.MAX_VALUE, 0, 4, 0, 4);
    }

    @Override
    public Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
        ByteBuf frame = null;
        try {
            frame = (ByteBuf) super.decode(ctx, in);
            if (null == frame) {
                return null;
            }

            ByteBuffer byteBuffer = frame.nioBuffer();
//            int totalLength = byteBuffer.limit();
            int requestIdLength = byteBuffer.getInt();

            byte[] requestIdByte = new byte[requestIdLength];

            byteBuffer.get(requestIdByte);
            String requestId = new String(requestIdByte);

            ResponseData responseData = new ResponseData();
            responseData.setRequestId(requestId);

            int resultBytesLen = byteBuffer.getInt();
            byte[] resultByte = new byte[resultBytesLen];
            byteBuffer.get(resultByte);
            responseData.setResultData(resultByte);

            return responseData;
        } catch (Exception e) {
            e.printStackTrace();
            ctx.channel().close();
        } finally {
            if (null != frame) {
                frame.release();
            }
        }
        return null;
    }

}
